
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter_cipher/flutter_cipher.dart';
import 'package:flutter_elf/utils/get_utils.dart';
import 'package:flutter_hls_parser/flutter_hls_parser.dart';
import '../download/file_utils.dart';
class M3u8Utils{

//  static saveFiles(List<String> urls,String savePath,String fileName)async{
//    for(int i = 0;i < urls.length;i++){
//      File file = File(savePath + '/$i.ts');
//      print("下载========>" + urls[i]);
//      File downFile = await FileUtils.downloadFileByUrl(urls[i], savePath + getFileName(urls[i]));
//      file.writeAsBytesSync(downFile.readAsBytesSync(),mode: FileMode.append);
//    }
//  }

  static saveFiles(List<String> urls,String savePath,String fileName)async{
    File file = await FileUtils.createFile(savePath + '/$fileName.ts');
    for(int i = 0;i < urls.length;i++){
      print("下载========>" + urls[i]);
      Uint8List downFile = await FileUtils.download(urls[i]);
//      Key key = Key.fromUtf8(key);
//      IV iv = IV.fromLength(16);
//      Symmetry aes = Cipher.getSymmetryInstance(AES(key, iv)));
//      aes.decrypt2String(encrypted);
//      String s = await Cipher2.decryptAesCbc128Padding7(String.fromCharCodes(downFile), key, await Cipher2.generateNonce());
//      file.writeAsStringSync(s,mode: FileMode.append);
    }
  }

  static String getFileName(String url){
    return url.substring(url.lastIndexOf('/')+1,url.lastIndexOf('.'));
  }
  static String key;
  static Future<List<String>> getTsList(String url)async{
    String preUrl = url.substring(0,url.lastIndexOf('/')+1);
    String m3u8Content = await HttpUtils.get(url);
    Uri playlistUri;
    var playList;
    try {
      playList = await HlsPlaylistParser.create().parseString(playlistUri, m3u8Content);
    } on ParserException catch (e) {
      print(e);
      return null;
    }
    if (playList is HlsMasterPlaylist) {//master需要重新请求一次
      print("Master======>"+playList.toString());
      return getTsList(preUrl + playList.mediaPlaylistUrls[0].path);
    } else if (playList is HlsMediaPlaylist) {
      key = await HttpUtils.get(preUrl + playList.segments[0].fullSegmentEncryptionKeyUri);
      return playList.segments.map<String>((e){
        return preUrl + e.url;
      }).toList();
    }
  }

  static Future<String> getKey(String keyUrl)async{
    String key = await HttpUtils.get(keyUrl);
    return key;
  }

}

String url = "https://eqmumbaby.com/20191224/75xQj0CC/index.m3u8";
void main()async{
//  List<String> urls = await M3u8Utils.getTsList(url);
//  print(urls);
//  await Future.delayed(Duration(seconds: 100));
  M3u8Utils.saveFiles(await M3u8Utils.getTsList(url), "D:/_m3u8测试数据", '测试');
  await Future.delayed(Duration(seconds: 100000));
}